using System;

namespace Mono4Delphi
{
	public interface ITSortThread: ITObject
	{
		void VisualSwap(int a, int b, int i, int j);
		void ShowMessage(string text);
		bool Terminated {get;}
	}
	
	
	class SortClass
	{
		public static void Main (string[] args)
		{
			Console.WriteLine ("Hello World!");
		}
		
		protected ITSortThread SortThread;
		
		public SortClass(ITSortThread aSortThread)
		{
			SortThread = aSortThread;
		}
		
		public virtual void Sort(ref int[] a)
		{
			
		}
	}
	
	class BubbleSort: SortClass
	{
		public BubbleSort(ITSortThread aSortThread): base(aSortThread)
		{}
		
		public override void Sort(ref int[] a)
		{
			for (int i = a.Length-1; i >= 0; i--)
			{
				for (int j = 0; j < a.Length-1; j++)
				{
					if (a[j] > a[j+1])
					{
						SortThread.VisualSwap(a[j], a[j+1], j, j+1);
						int t = a[j];
						a[j] = a[j+1];
						a[j+1] = t;
						if (SortThread.Terminated)
							return;
					}
				}
			}
		}
	}
	
	class SelectionSort: SortClass
	{
		public SelectionSort(ITSortThread aSortThread): base(aSortThread)
		{}
		
		public override void Sort(ref int[] a)
		{
			int i = 0;
			int j = 0;
			int arrlen = a.Length;
			
			for (i = 0; i < arrlen-1; i++)
			{
				for (j = arrlen-1; j > i; j--)
				{
					if ((i < 0)||(i > 113)||(j < 0)||(j > 113))
						SortThread.ShowMessage(" i = " + i.ToString()+ " j = " + j.ToString());
					
					if (a[i] > a[j])
					{
						SortThread.VisualSwap(a[i], a[j], i, j);
						int t = a[i];
						a[i] = a[j];
						a[j] = t;
						if (SortThread.Terminated)
							return;
					}

					
				}
			}
			
				
		}
	}
	
	class QuickSort: SortClass
	{
		public QuickSort(ITSortThread aSortThread): base(aSortThread)
		{}
		
		private void internalQuickSort(ref int[] a, int iLo, int iHi)
		{
			int lo = iLo;
			int hi = iHi;
			int mid = a[(lo + hi)/2];
			do {
				while (a[lo] < mid) {
					lo++;
				}
				while (a[hi] > mid) {
					hi--;
				}
				if (lo <= hi)
				{
					SortThread.VisualSwap(a[lo], a[hi], lo, hi);
					int t = a[lo];
					a[lo] = a[hi];
					a[hi] = t;
					lo++;
					hi--;
				}
			} while (lo <= hi);
			if (hi > iLo)
				internalQuickSort(ref a, iLo, hi);
			if (lo < iHi)
				internalQuickSort(ref a, lo, iHi);
			if (SortThread.Terminated)
							return;
		}
		
		public override void Sort(ref int[] a)
		{
			internalQuickSort(ref a, 0, a.Length-1);
		}
	}
	
}


